import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/views/Login'
import Home from '@/views/Home'
import Main from '@/views/Main/main.vue'
import Articles from '@/views/Main/articles.vue'
import Images from '@/views/Main/images.vue'
import Publish from '@/views/Main/publish.vue'
import Comments from '@/views/Main/comments.vue'
import Fans from '@/views/Main/fans.vue'
import Settings from '@/views/Main/settings.vue'

Vue.use(VueRouter)

const routes = [{
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'login',
    component: Login
  },
  {
    path: '/home',
    name: 'home',
    component: Home,
    redirect: '/main',
    children: [{
        path: '/main',
        name: 'main',
        component: Main,
      },
      {
        path: '/articles',
        name: 'articles',
        component: Articles
      }, {
        path: '/images',
        name: 'images',
        component: Images
      },
      {
        path: '/publish',
        name: 'publish',
        component: Publish
      },
      {
        path: '/comments',
        name: 'comments',
        component: Comments
      }, {
        path: '/fans',
        name: 'fans',
        component: Fans
      }, {
        path: '/settings',
        name: 'settings',
        component: Settings
      }
    ]
  }
]

const router = new VueRouter({
  routes
})
router.beforeEach((to, from, next) => {
  const token = sessionStorage.getItem('token')
  if (to.path !== '/login') {
    if (token) {
      next()
    } else {
      next('/login')
    }
  }
  next()
})

// 解决编程式路由往同一地址跳转时会报错的情况
const originalPush = VueRouter.prototype.push
const originalReplace = VueRouter.prototype.replace
VueRouter.prototype.push = function push(location, onResolve, onReject) {
  // if (onResolve || onReject) {
  //   return originalPush.call(this, location, onResolve, onReject)
  // }
  return originalPush.call(this, location).catch(err => err)
}
VueRouter.prototype.replace = function push(location, onResolve, onReject) {
  // if (onResolve || onReject) {
  //   return originalReplace.call(this, location, onResolve, onReject)
  // }
  return originalReplace.call(this, location).catch(err => err)
}


export default router
